$(document).ready(function() {

	var param = parseUrlSearch();
	var pageData = {
		page: 1,
		size: 8
	}

	$.init();
	
	$(document).on('click', '.j-talk', talkHandle);
	$(document).on('click', '.j-date', dateHandle);
	$(document).on('click', '.j-edit', editHandle);
	$(document).on('click', '.j-return', talkHandle);
	$(document).on('click', '.pull-left', returnHanlde);
	$('.infinite-scroll-bottom').on('infinite', infiniteHandle());

	updatePartialHtml();

	function returnHanlde() {
		if(param && param.from == 'remind') {
			window.location = './travel_remind.html';
		}else{
			window.location = './travel_list.html';
		}
	}

	fetchInfo(function(data) {
		var personHtml = getPersonInfoHtml(data);
		var warchHtml = getWatchHtml(data);
		var travelHtml = getTravelListHtml(data);

		$('.content .person-info').html(personHtml||'<div class="no-data">暂无行程</div>');
		$('.content .watch .card').html(warchHtml||'<div class="no-data">暂无行程</div>');
		$('.content .travel-list .card').html(travelHtml||'<div class="no-data">暂无行程</div>');
	});

	function talkHandle(e) {
		var $target = $(e.currentTarget);
		var isReturn = $target.hasClass('j-return');
		var text = isReturn ? '' : '';
		$.confirm('<textarea></textarea>', function(elem) {
			var val = $(elem).find('textarea').val();
            if(!val) {
                $.alert('内容不能为空！');
                talkHandle(e);
                return;
            }
			$.ajax({
				url: HOST + '/api/comment/create',
				type: 'post',
				data: JSON.stringify({
					openid: SELFID,
					message: $(elem).find('textarea').val(),
					parentid: isReturn ? $target.closest('.talk-item').data('parent') : '',
					messagedOpenid: isReturn ? $target.closest('.talk-item').data('id') : param.targetid
				}),
				success: function(res) {
					if(res.content == 'success') {
						$.alert('留言成功！');
						pageData.page = 1;
						$('.content').scrollTop(0);
						renderTalkList();
						return;
					}
					$.alert('留言失败！');
				},
				error: function() {
					$.alert('留言失败！');
				}
			})
		});
	}

	function dateHandle() {
		$.ajax({
			type: 'post',
			url: HOST + '/api/travel/date',
			data: JSON.stringify({
				"openid": SELFID,
   				"datedOpenid": param.targetid
			}),
			success: function(data) {
				if(data.content == 'success') {
					$.alert('请求成功');
					return;
				}
				$.alert(data.content);
			},
			error: function() {
				$.alert('error!');
			}
		});
	}

	function updatePartialHtml() {
		if(param && param.targetid) {
			var $bar = $('.page .bar');
			$('button', $bar).remove();
			$('h1', $bar).html('详细信息');
			$('.content-block').show();
			renderTalkList();
		}
	}

	function renderTalkList() {
		$('.talk-list').show();
		fetchTalkList(function (list) {
			var html = list.reduce(function (memo, item){
				return memo + getTalkHtml(item) + item.children.reduce(function (m, i) {
					return m + getTalkHtml(i);
				}, '');
			}, '');
			if(pageData.page == 1) {
				$('.talk-list .card').html(html||'<div class="no-data">暂无留言</div>');
			}else{
				$('.talk-list .card').append(html);
			}
			pageData.page++;
			$('.talk-list .infinite-box').html(list.length == pageData.size ? '<div class="infinite-scroll-preloader"><div class="preloader"></div></div>' : '');
		});
	}

	function fetchTalkList(callback) {
		$.ajax({
			url: HOST + '/api/comment/list',
			data: {
				openid: param.targetid || SELFID,
				page: pageData.page,
				size: pageData.size
			},
			success: function(data) {
				callback && callback(data.content);
			}
		})
	}

	function fetchInfo(callback) {
		var strArray = [];
		strArray.push('openid=' + (param.targetid || SELFID));
		if(param.targetid) {
			strArray.push('recordOpenid=' + SELFID);
		}
		strArray = strArray.join('&');
		// param = '?targetid=oJEP8t03z5DrCC5X9ochRlh7i2DY&selfid=oJEP8t_rnBFzEfuA-fqwDKdWbytA';
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/get' + (strArray ? '?' + strArray : ''),
			success: function(data) {
				callback && callback(data);
			}
		});
	}

	function flattenArray(list, parent) {
		var result = [];
		for(var i = 0; i < list.length; i++){
			if(parent) {
				i.parent = parent.createdAt
			}
			result.push(list[i]);
			if(list[i].children && list[i].children.length > 0) {
				result = result.concat(arguments.callee(list[i].children));
			}
		}
		return result;
	}

	function editHandle() {
		window.location = './travel_insert.html?edit=1'
	}

	function infiniteHandle() {
        var loading = false;
        var I = 0;
        return function() {
        	if(!param.targetid) {
        		return;
        	}
            if(loading || $('.infinite-scroll-preloader').length == 0) {
                return;
            }
            loading = true;
            if(I) {
                clearTimeout(I);
            }
            I = setTimeout(function() {
                renderTalkList();
                loading = false;
            }, 500);
        }
    }

	function getPersonInfoHtml(data) {
		var labels = data.labels.reduce(function(memo, label) {
			return memo + '<span class="button button-fill button-label">'+label+'</span>';
		}, '');
		return '<div class="img"><img src="'+data.imgUrl+'"></div>\
                <div class="text">\
                    <div>\
                        <span class="name">'+data.name+'</span>\
                        <div>微信号：'+(data.is_date?data.wxid:(data.wxid.slice(0,-3)+'***'))+'</div>\
                    </div>\
                    <div>\
                        <span>'+['','男','女'][data.gender]+'</span>\
                        <em>|</em>\
                        <span>'+data.age+'岁</span>\
                        <em>|</em>\
                        <span>'+data.peerNum+'人</span>\
                    </div>\
                    <div style="margin-top:0.1rem;">'+labels+'</div>\
                </div>\
                <div class="desc '+(data.supportTeams.length == 0?'g-hide':'')+'">支持的球队：'+(data.supportTeams.join(' '))+'</div>\
                <div class="desc">简介：'+(data.description||'无')+'</div>\
                <div class="viewnum">'+data.viewNum+'人已查看</div>'
	}

	function getWatchHtml(data) {
		return '<div>\
	                <span>'+data.fromCity+'&nbsp;-&nbsp;'+data.toCity+'</span>\
	                <em>|</em>\
	                <span>'+data.startDate+'&nbsp;-&nbsp;'+data.returnDate+'</span>\
	            </div>\
	            <div>'+data.matches.join('、')+'</div>\
	            <div>\
	                <span>'+data.vehicle+'</span>\
	                <em>|</em>\
	                <span>'+(data.vehicleNo || '未填写航班（车次）')+'</span>\
	            </div>';
	}

	function getTravelListHtml(data) {
		return data.travels.reduce(function(memo, travel) {
			return memo+'<div class="travel-item">\
							<div class="city">'+travel.city+'</div>\
                    		<div>'+travel.startDate+'&nbsp;-&nbsp;'+travel.endDate+'</div>\
                    		<div>\
	                        	<span>'+travel.vehicle+'</span>\
	                        	<em>|</em>\
	                        	<span>'+(travel.vehicleNo || '未填写航班（车次）')+'</span>\
	                    	</div>\
	                    	<div>\
	                        	<span>'+(travel.hotelName?'已预订酒店':'未预定酒店')+'</span>\
	                        	<em>'+(travel.hotelName?'|':'')+'</em>\
	                        	<span>'+(travel.hotelName||'')+'</span>\
	                    	</div>\
	                    </div>';
		}, '');	
	}

	function getTalkHtml(data) {
		return '<div class="talk-item '+(data.parentId?'son-item':'')+'">\
                    <div class="first"><span>'+data.name+'</span>'+(data.parentId?('回复<span>'+data.messagedName+'</span>'):'')+parseDateStamp(data.createdAt)+'</div>\
                    <div class="second">'+data.content+'</div>\
                </div>';
	}
})
